import { useState, useRef } from 'react';

// AI API相关的hook
export const useAIApi = () => {
	const [isAssistant, setIsAssistant] = useState(false);
	// 使用 Map 来跟踪进行中的请求
	const pendingRequests = useRef(new Map());
	// 使用 Map 来跟踪 AbortController
	const abortControllers = useRef(new Map());
	// 使用 Map 来存储请求结果
	const requestResults = useRef(new Map());

	// 生成请求的唯一标识符
	const getRequestKey = (endpoint: string, params: any) => {
		return `${endpoint}_${JSON.stringify(params)}`;
	};

	// 调用Qwen3 API的通用函数
	const callQwen3API = async (
		message: string,
		prompt?: string,
		apiKey = 'sk-eTt8yC56stXL66an79D311Eb85274973AfD9914337F7003b'
	) => {
		// 创建请求参数对象用于生成唯一标识符
		const requestParams = { message, prompt, apiKey };
		const endpoint = 'https://api.edgefn.net/v1/chat/completions';
		const requestKey = getRequestKey(endpoint, requestParams);

		// 检查是否有相同的请求正在进行
		if (pendingRequests.current.has(requestKey)) {
			console.log('防止重复请求: 相同请求正在进行中');
			return pendingRequests.current.get(requestKey);
		}

		// 检查是否有缓存的结果
		if (requestResults.current.has(requestKey)) {
			console.log('返回缓存结果');
			return requestResults.current.get(requestKey);
		}

		// 创建 AbortController 用于取消请求
		const abortController = new AbortController();
		abortControllers.current.set(requestKey, abortController);

		// 创建一个新的 Promise 并存储在 Map 中
		const requestPromise = (async () => {
			try {
				const response = await fetch(endpoint, {
					method: 'POST',
					headers: {
						Authorization: `Bearer ${apiKey}`,
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({
						model: 'Qwen3-30B-A3B-FP8',
						messages: [{ role: 'user', content: message }],
						prompt: prompt
					}),
					signal: abortController.signal
				});

				if (!response.ok) {
					throw new Error(`HTTP error! Status: ${response.status}`);
				}

				const result = await response.json();
				// 存储结果以便后续使用
				requestResults.current.set(requestKey, result);
				return result;
			} catch (error: any) {
				// 检查是否是取消请求导致的错误
				if (error.name === 'AbortError') {
					console.log('请求已被取消');
					return { cancelled: true };
				}
				console.error('Error calling Qwen3 API:', error);
				throw error;
			} finally {
				// 请求完成后从 Maps 中移除
				pendingRequests.current.delete(requestKey);
				abortControllers.current.delete(requestKey);
			}
		})();

		// 将请求 Promise 存储在 Map 中
		pendingRequests.current.set(requestKey, requestPromise);
		return requestPromise;
	};

	// 调用Qwen3 API的对话列表版本
	const callQwen3APIList = async (
		message: any[],
		apiKey = 'sk-eTt8yC56stXL66an79D311Eb85274973AfD9914337F7003b'
	) => {
		// 创建请求参数对象用于生成唯一标识符
		const requestParams = { message, apiKey };
		const endpoint = 'https://api.edgefn.net/v1/chat/completions';
		const requestKey = getRequestKey(endpoint, requestParams);

		// 检查是否有相同的请求正在进行
		if (pendingRequests.current.has(requestKey)) {
			console.log('防止重复请求: 相同请求正在进行中');
			return pendingRequests.current.get(requestKey);
		}

		// 创建 AbortController 用于取消请求
		const abortController = new AbortController();
		abortControllers.current.set(requestKey, abortController);

		// 创建一个新的 Promise 并存储在 Map 中
		const requestPromise = (async () => {
			try {
				const response = await fetch(endpoint, {
					method: 'POST',
					headers: {
						Authorization: `Bearer ${apiKey}`,
						'Content-Type': 'application/json'
					},
					body: JSON.stringify({
						model: 'Qwen3-30B-A3B-FP8',
						messages: message,
						prompt: '作为一名会议记录人员,善于总结会议纪要'
					}),
					signal: abortController.signal
				});

				if (!response.ok) {
					throw new Error(`HTTP error! Status: ${response.status}`);
				}

				const result = await response.json();
				return result;
			} catch (error: any) {
				// 检查是否是取消请求导致的错误
				if (error.name === 'AbortError') {
					console.log('请求已被取消');
					return { cancelled: true };
				}
				console.error('Error calling Qwen3 API:', error);
				throw error;
			} finally {
				// 请求完成后从 Maps 中移除
				pendingRequests.current.delete(requestKey);
				abortControllers.current.delete(requestKey);
			}
		})();

		// 将请求 Promise 存储在 Map 中
		pendingRequests.current.set(requestKey, requestPromise);
		return requestPromise;
	};

	// 取消所有进行中的请求
	const cancelAllRequests = () => {
		for (const [requestKey, abortController] of abortControllers.current.entries()) {
			abortController.abort();
		}
		abortControllers.current.clear();
		pendingRequests.current.clear();
	};

	// 取消特定请求
	const cancelRequest = (endpoint: string, params: any) => {
		const requestKey = getRequestKey(endpoint, params);
		const abortController = abortControllers.current.get(requestKey);
		if (abortController) {
			abortController.abort();
			abortControllers.current.delete(requestKey);
			pendingRequests.current.delete(requestKey);
		}
	};

	// 清除缓存的结果
	const clearRequestResults = () => {
		requestResults.current.clear();
	};

	return {
		callQwen3API,
		callQwen3APIList,
		isAssistant,
		setIsAssistant,
		cancelAllRequests,
		cancelRequest,
		clearRequestResults
	};
};
